import { VxeUI } from 'vxe-pc-ui';
import { usePermissionStore } from '@/store';
// import { useRouter, useRoute } from 'vue-router';
// const router = useRouter();
// const route = useRoute();
import { ElMessage } from 'element-plus';
export function useVxeGridUtils() {
  /**
   * 返回上一级
   * @param {*} tagsViewStore
   * @param {*} route
   * @param {*} router
   */
  const previousHandle = (tagsViewStore, route, router) => {
    const { visitedViews } = tagsViewStore;
    const currentView = visitedViews[visitedViews.length - 1];
    tagsViewStore.delView(currentView).then((res) => {
      const parentView = res.visitedViews.find(
        (view) => view.path === route.query._parent,
      );
      router.push(parentView ? parentView.fullPath : '/');
    });
  };

  /**
   * 单选框选中行处理，向父窗口发送选中行数据
   * @param {Object} row 当前行数据
   * @param {Object} route 当前路由对象
   */
  const radioChangeHandle = (row, route) => {
    // 如果是作为表格选择弹窗时
    if (route.query.selection) {
      const safeCheckedRows = [
        {
          value: row[route.query.value],
          label: row[route.query.label],
        },
      ];
      window.parent.postMessage(
        {
          action: 'selectRow',
          safeCheckedRows: JSON.parse(JSON.stringify(safeCheckedRows)),
        },
        '*',
      );
    }
  };

  /**
   * 复选框选中行处理，向父窗口发送选中行数据
   * @param {*} records
   * @param {*} route
   */
  const checkBoxChangeHandle = (records, route) => {
    // 如果是作为表格选择弹窗时
    if (route.query.selection) {
      // 从选中的行中，把指定的字段取出来，组成一个新的对象数组
      const safeCheckedRows = records.map((item) => ({
        value: item[route.query.value],
        label: item[route.query.label],
      }));
      window.parent.postMessage(
        {
          action: 'selectRow',
          safeCheckedRows: JSON.parse(JSON.stringify(safeCheckedRows)),
        },
        '*',
      );
    }
  };

  /**
   * 生成行拖拽排序的参数
   * @param {*} event
   * @param {*} gridRef
   */
  const getDragParams = (event, gridRef, column) => {
    // 类型检查和边界条件检查
    if (!event || !event._index || !event.oldRow || !event.newRow) {
      throw new Error('非法参数');
    }
    // 如果行的顺序没有改变，则直接返回
    // const { oldIndex, newIndex } = event._index;
    // const indexDelta = oldIndex - newIndex;
    // if (indexDelta === 0) return;

    // 获取当前表格中 sort 列的排序规则
    const sortOrder = gridRef
      .getSortColumns()
      .find((item) => item.field === column)?.order;
    if (!sortOrder) {
      throw new Error('未按照此列排序，请先排序');
    }
    // 准备拖拽排序的参数
    const { oldRow, newRow, dragPos, dragToChild } = event;
    return {
      newId: newRow.id,
      oldId: oldRow.id,
      dragPos,
      orderBy: sortOrder,
      dragToChild: dragToChild ? 'true' : 'false',
    };
  };

  /**
   * 工具栏左侧，将按钮渲染为El-button样式的按钮
   * @param {*} buttons
   * @returns
   */
  const renderToolbarButton = (buttons) => {
    const permissionStore = usePermissionStore();
    return buttons.map((button) => {
      const reactiveButton = reactive({
        ...button,
        buttonRender: {
          name: 'RaToolbarButtonRender',
          events: {
            click: (event, params) => {
              const runAction = async () => {
                console.log('RaToolbarButtonRender click event:', {
                  button,
                  event,
                });
                if (
                  params &&
                  params.$grid &&
                  typeof params.$grid.triggerToolbarBtnEvent === 'function'
                ) {
                  params.$grid.triggerToolbarBtnEvent(button, event);
                } else {
                  console.error(
                    'Error: $grid or triggerToolbarBtnEvent is not available.',
                    { params, button, event },
                  );
                }
              };

              try {
                runAction();
              } catch (error) {
                if (error.message && error.message.includes('No match for')) {
                  (async () => {
                    try {
                      // 1. 清理掉所有旧的动态路由
                      permissionStore.resetRouter();
                      // 2. 重新生成并添加新的动态路由
                      await permissionStore.generateRoutes();
                      console.log('[HMR Recovery] Routes regenerated.');
                      // 3. 重新尝试执行之前的操作！
                      console.log('[HMR Recovery] Retrying the action...');
                      runAction();
                    } catch (recoveryError) {
                      console.error(
                        '[HMR Recovery] Failed to recover. Forcing page reload.',
                        recoveryError,
                      );
                      // 如果恢复失败，可以考虑最终的兜底方案：强制刷新
                      window.location.reload();
                    }
                  })();
                }
              }
            },
          },
        },
      });
      return reactiveButton;
    });
  };

  /**
   * 工具栏右侧，将按钮渲染为El-button样式的按钮
   * @param {*} buttons
   * @returns
   */
  const renderToolbarTool = (buttons) => {
    return buttons.map((button) => {
      const reactiveButton = reactive({
        ...button,
        toolRender: {
          name: 'RaToolbarToolRender',
          events: {
            click: (event, params) => {
              params.$grid.triggerToolbarTolEvent(button, event);
            },
          },
        },
      });
      return reactiveButton;
    });
  };

  const generateCode = async (API, isApi, route) => {
    const overwrite = ref(true);
    const radioOptions = [
      { label: '覆盖源码', value: true },
      { label: '备份源码', value: false },
    ];
    try {
      const result = await VxeUI.modal.confirm({
        title: `生成代码`,
        width: 400,
        slots: {
          default: () => {
            return [
              h('span', {}, '是否允许覆盖已存在的源码？'),
              h(
                ElRadioGroup,
                {
                  modelValue: overwrite.value,
                  'onUpdate:modelValue': (value) => {
                    overwrite.value = value;
                  },
                },
                () =>
                  radioOptions.map((option) =>
                    h(ElRadio, {
                      label: option.label,
                      value: option.value,
                    }),
                  ),
              ),
            ];
          },
        },
      });
      if (result === 'confirm') {
        const params = {
          id: route.query.id,
          overwrite: overwrite.value,
        };
        if (isApi.value) {
          const { code, message } = await API.genApiCode(params);
          code === 200 && ElMessage.success(message);
        } else {
          const { code, message } = await API.genAdminCode(params);
          code === 200 && ElMessage.success(message);
        }
      }
    } catch (error) {
      console.log(error.message);
      ElMessage.error(error.message);
    }
  };

  return {
    previousHandle,
    checkBoxChangeHandle,
    radioChangeHandle,
    getDragParams,
    renderToolbarButton,
    renderToolbarTool,
    generateCode,
  };
}
